package com.learner.course.service.impl;

import com.learner.common.client.oss.OssFileClient;
import com.learner.common.exception.ExceptionUtil;
import com.learner.common.exception.RestException;
import com.learner.course.repository.CourseBaseRepository;
import com.learner.course.repository.TeacherRepository;
import com.learner.course.service.TeacherService;
import com.learner.pojo.course.CourseBase;
import com.learner.pojo.course.Teacher;
import com.learner.pojo.course.expand.PageVariableTeacher;
import com.learner.pojo.page.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * @author ice2020x
 * @Date: 2023/3/8
 * @Description: 讲师
 **/
@Service
@Slf4j
public class TeacherServiceImpl implements TeacherService {


    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private OssFileClient ossFileClient;

    @Autowired
    private CourseBaseRepository courseBaseRepository;

    @Override
    public List<Teacher> getTeacherListByState(Integer state) {
        if (state == null) {
            throw ExceptionUtil.createException(RestException.class, 2000005);
        }
        if (!(state == 1 || state == 0)) {
            state = 0;
        }
        return teacherRepository.findAllTeachersByState(state);
    }


    @Override
    public List<Teacher> list() {
        return teacherRepository.findAll();
    }


    @Override
    public void removeById(String id) {
        teacherRepository.deleteById(id);
    }

    @Override
    public PageResult<Teacher> listPageByPathVariable(PageVariableTeacher pageVariable) {
        Sort sort = Sort.by(Sort.Direction.ASC, "sort");
        Pageable pageable = PageRequest.of(pageVariable.getPageNum() - 1, pageVariable.getPageSize(), sort);
        Specification<Teacher> specification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (null != pageVariable.getName() && !"".equals(pageVariable.getName())) {
                list.add(criteriaBuilder.like(root.get("name"), "%" + pageVariable.getName() + "%"));
            }
            if (null != pageVariable.getLevel() && pageVariable.getLevel() != 0) {
                list.add(criteriaBuilder.equal(root.get("level"), pageVariable.getLevel()));
            }
            if (null != pageVariable.getIntro() && !"".equals(pageVariable.getIntro())) {
                list.add(criteriaBuilder.like(root.get("intro"), "%" + pageVariable.getIntro() + "%"));
            }
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Page<Teacher> teacherPage = teacherRepository.findAll(specification, pageable);

        return new PageResult<>(teacherPage.getTotalElements(), teacherPage.getContent());
    }

    @Override
    public Teacher save(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    @Override
    public Teacher getTeacherById(String id) {
        log.info("根据id查询讲师信息，id{}", id);
        return teacherRepository.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<String> ids) {
        log.info("根据id列表逻辑删除，id列表:{}", ids);
        teacherRepository.deleteBatch(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteAuthenticByIds(List<String> ids) {
        log.info("根据id列表真实删除，id列表:{}", ids);
        teacherRepository.deleteBatchAuthentic(ids);

    }

    @Override
    public List<Map<String, Object>> getListNameByKey(String key) {
        return teacherRepository.findAllCategories("%" + key + "%");
    }

    @Override
    public List<Teacher> getTeacherListByName(String name, Integer state) {
        if (StringUtils.isNotBlank(name)) {
            throw ExceptionUtil.createException(RestException.class, 2000005);
        }
        if (state == null) {
            throw ExceptionUtil.createException(RestException.class, 2000005);
        }
        if (!(state == 1 || state == 0)) {
            state = 0;
        }

        return teacherRepository.findAllTeachersByName("%" + name + "%", state);
    }

    @Override
    public boolean removeAvatarById(String id) {
        Optional<Teacher> optional = teacherRepository.findById(id);
        if (!optional.isPresent()) {
            return false;
        }
        Teacher teacher = optional.get();
        String avatar = teacher.getAvatar();
        if (StringUtils.isBlank(avatar)) {
            return false;
        }
        ossFileClient.removeFile(avatar);
        return true;
    }

    @Override
    public Map<String, Object> selectTeacherInfoById(String id) {
        Optional<Teacher> optional = teacherRepository.findById(id);
        Teacher teacher = null;
        if (optional.isPresent()) {
            teacher = optional.get();
        }
        List<CourseBase> courseBases = courseBaseRepository.findByUserId(id);
        Map<String, Object> map = new HashMap<>(2);
        map.put("teacher", teacher);
        map.put("courseList", courseBases);
        return map;
    }
}
